﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;

namespace Minestorm.Evolved.IoC
{
	public class ConstructionMapFactory
	{
		public ConstructionMap CreateFromConcreteType(Type concreteType)
		{
			ConstructionMap constructionMap = new ConstructionMap();

			ConstructorInfo[] constructors = concreteType.GetConstructors();

			Array.Sort(constructors, new ConstructorInfoComparer());

			foreach (ConstructorInfo constructor in constructors)
			{
				Type[] parameterTypes = GetConstructionParameters(constructor);
				if (IsAutoWireCandidate(parameterTypes))
					constructionMap.Types.Add(parameterTypes);
			}

			return constructionMap;
		}

		public Boolean IsAutoWireCandidate(Type[] parameterTypes)
		{
			foreach (Type parameterType in parameterTypes)
				if (!parameterType.IsInterface)
					return false;

			return true;
		}

		public Type[] GetConstructionParameters(ConstructorInfo constructor)
		{
			List<Type> types = new List<Type>();

			foreach (ParameterInfo parameter in constructor.GetParameters())
				types.Add(parameter.ParameterType);

			return types.ToArray();
		}
	}
}
